<template>
	<view class="add-container">
		<u-form v-show="tabIndex === 0"  :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
			:rules="rules" ref="uForm1" class="form-container">
			<view class="header">
				<view class="logo">访</view>
				<view class="title">被访人信息</view>
			</view>
			<u-form-item label="被访人姓名" prop="visitedNameLabel" required borderBottom v-show="showVisited">
				<u-input fontSize="14px"   readonly v-model="form.visitedNameLabel" border="none" placeholder=""></u-input>
			</u-form-item>
			<u-form-item label="被访人电话" prop="visitedPhone" required borderBottom>
				<u-input fontSize="14px"  type="number" v-model="form.visitedPhone" border="none" maxlength="11"
					placeholder="请输入被访人电话"></u-input>
			</u-form-item>
		

		</u-form>

		<u-form :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
			:rules="rules" ref="uForm2" class="form-container " :class="tabIndex === 0 ? 'mg-top30' : ''">
			<view class="header">
				<view class="logo">客</view>
				<view class="title">访客信息</view>
			</view>

			<u-form-item label="访客姓名" prop="appointName" required borderBottom>
				<u-input fontSize="14px"   v-model="form.appointName" border="none" placeholder="请输入访客姓名"></u-input>
			</u-form-item>
			<u-form-item label="访客电话" prop="appointPhone" required borderBottom>
				<u-input fontSize="14px"  type="number" v-model="form.appointPhone" border="none" maxlength="11"
					placeholder="请输入访客电话"></u-input>
			</u-form-item>
			<u-form-item label="访客单位" prop="appointDept" required borderBottom>
				<u-input fontSize="14px"  v-model="form.appointDept" border="none" maxlength="11" placeholder="请输入访客单位"></u-input>
			</u-form-item>
			<u-form-item label="来访人数" prop="num" required borderBottom>
				<u-input fontSize="14px"  type="number" v-model="form.num" border="none" maxlength="5"
					placeholder="请输入来访人数"></u-input>
			</u-form-item>
			<!-- <u-form-item label="访客身份证" prop="cardNo" borderBottom>
				<u-input fontSize="14px"  type="idcard" v-model="form.cardNo" border="none" maxlength="18"
					placeholder="请输入访客身份证"></u-input>
			</u-form-item> -->

			<u-form-item label="到访日期" prop="appointTime" required borderBottom @click="showPicker">
				<u-input fontSize="14px"  style="pointer-events: none;  user-select: none;min-width: 300rpx;" v-model="form.appointTime"
					border="none" maxlength="20" placeholder="请输入到访日期"></u-input>
				<u-datetime-picker ref="datetimePicker"  :minDate="minDate" :show="showDatePicker" :formatter="formatter"
					v-model="nowDate" @confirm="handlePickDate" @cancel="showDatePicker = false"
					mode="datetime"></u-datetime-picker>
			</u-form-item>

			<u-form-item label="来访事由" prop="appointRemark" required borderBottom @click="showPickerRemark">
				<u-input fontSize="14px"  style=" pointer-events: none; user-select: none;min-width: 300rpx;" v-model="form.appointRemark"
				border="none" maxlength="20" placeholder="请输入来访事由"></u-input>

				<u-picker :show="showRemarkPicker" @confirm="handlePickRemark" @cancel="showRemarkPicker = false"
					:columns="remarks"></u-picker>
			</u-form-item>
		</u-form>

		<u-form :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
			:rules="rules" ref="uForm3" class="form-container mg-top30">
			<view class="header">
				<view class="logo">同</view>
				<view class="title">同行人</view>
			</view>

			<u-cell-group>
				<u-cell v-for="(person,index) in list" @click="editCompanions(index)" :title="person.name"
					:isLink="true"></u-cell>
				<u-cell @click="addCompanions" :isLink="true" value="新增"></u-cell>
			</u-cell-group>
		</u-form>

		<view class="submit">
			<u-button color="#920076" :loading="loading" loadingText="提交中" @click="submit">提交</u-button>
		</view>

		<u-notify ref="uNotify" message="预约成功"></u-notify>
	</view>
</template>

<script>
	import moment from 'moment';
	import {
		getOpenid,
		desensitizeName
	} from "@/common/permission.js"
	export default {
		data() {
			return {
				loading: false,
				showVisited: false,
				showRemarkPicker: false,
				remarks: [['业务交流', '公司参观', '技术交流', '参加会议', '供应商施工', '面试', '其他']],
				//真实的被访人姓名
				realVisitedName: '',
				openid: '',
				tabIndex: 0,
				minDate: Number(new Date()),
				nowDate: Number(new Date()),
				showDatePicker: false,
				list: [], //同行人信息
				form: {
					visitedNameLabel: '',
					visitedName: '',
					visitedPhone: '',
					appointName: '',
					appointPhone: '',
					cardNo: '',
					appointDept: '',
					appointTime: '',
					num: ''
				},
				rules: {
					visitedName: [{
						required: true,
						message: '请输入被访人姓名',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							if (this.realVisitedName &&
								this.realVisitedName != this.form.visitedName) {
								return false
							} else {
								return true
							}
						},
						message: '请输入正确的被访人姓名',
						// 触发器可以同时用blur和change
						trigger: ['blur'],
					}],
					visitedPhone: [{
							required: true,
							message: '请输入被访人电话',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['blur'],
						}, {
							asyncValidator: (rule, value, callback) => {
								this.$request({
									url: '/appoint/getUserInfo?phone=' + value
								}).then(res => {
									if (res.data) {
										this.form.visitedNameLabel = desensitizeName(res.data.name)
										this.form.visitedName = res.data.name
										this.realVisitedName = res.data.name
										this.showVisited = true
										callback()
									} else {
										this.showVisited = false
										this.form.visitedNameLabel = ''
										this.form.visitedName = ''
										callback(new Error('被访人不存在或没权限访问'));
									}
								}).catch(() => {
									this.showVisited = false
									this.form.visitedNameLabel = ''
									this.form.visitedName = ''
									callback(new Error('被访人不存在或没权限访问'));
								})

							},
							trigger: ['blur'],
							// 如果是异步校验，无需写message属性，错误的信息通过Error抛出即可
							// message: 'xxx'
						}
					],
					appointName: [{
						required: true,
						message: '请输入访客姓名',
						trigger: ['blur', 'change']
					}],
					appointPhone: [{
							required: true,
							message: '请输入访客电话',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					],
					appointDept: [{
						required: true,
						message: '请输入访客单位',
						trigger: ['blur', 'change']
					}],
					num: [{
						required: true,
						message: '请输入来访人数',
						trigger: ['blur', 'change']
					}],
					cardNo: [{
							required: false,
							message: '请输入访客身份证',
							trigger: ['blur', 'change']
						},
						// {
						// 	validator: (rule, value, callback) => {
						// 		// 上面有说，返回true表示校验通过，返回false表示不通过
						// 		// uni.$u.test.mobile()就是返回true或者false的
						// 		const regex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
						// 		return regex.test(value);
						// 	},
						// 	message: '请输入正确的身份证',
						// 	// 触发器可以同时用blur和change
						// 	trigger: ['blur'],
						// },
					],
					appointRemark: [{
						required: true,
						message: '请输入来访事由',
						trigger: ['blur', 'change']
					}],
					appointTime: [{
						required: true,
						message: '请输入到访日期',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		onShow() {
			const companions = uni.getStorageSync("companions") || []
			console.log("on show=============", companions)
			if (companions) {
				this.list = companions
				uni.removeStorageSync("companions")
			}
		},
		onReady() {
			// this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		computed: {
			lstyle() {
				return {
					fontSize: '32rpx'
				}
			}
		},
		async onLoad(e) {
			console.log("onLoad===============")
			this.openid = await getOpenid()
			if (e.tabIndex) {
				this.tabIndex = parseInt(e.tabIndex)
				uni.setNavigationBarTitle({
					title: this.tabIndex === 0 ? '新增我的预约' : '新增代客预约'
				})
				if(this.tabIndex === 1){
					//代客预约
					//  根据openid 查询员工信息
					this.$request({
						url: '/appoint/getUserRole?openid=' + this.openid
					}).then(res => {
						if(res.data && res.data.openid){
							// 被访人自动回填
							this.form.visitedName = res.data.name
							this.form.visitedPhone = res.data.phone
						}
					})
				}
				
			}



		},
		methods: {
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			addCompanions() {
				if (this.list && this.list.length > 0) {
					uni.setStorageSync("companions", this.list)
				}
				uni.navigateTo({
					url: "/pages/reservation/companions"
				})
			},
			editCompanions(index) {
				if (this.list && this.list.length > 0) {
					uni.setStorageSync("companions", this.list)
				}
				uni.navigateTo({
					url: "/pages/reservation/companions?index=" + index + '&status=0'
				})
			},
			handlePickDate(e) {
				this.showDatePicker = false
				console.log(moment(e.value).format('YYYY-MM-DD HH:mm:ss'), "tttttttt")
				this.form.appointTime = moment(e.value).format('YYYY-MM-DD HH:mm')
				console.log(this.form.appointTime, "ggggggg")
			},
			showPicker() {
				this.showDatePicker = true
			},
			showPickerRemark() {
				this.showRemarkPicker = true
			},
			handlePickRemark(e) {
				this.showRemarkPicker = false
				this.form.appointRemark = e.value[0]
			},
			submit() {
				this.$refs.uForm1.validate().then(res => {
					this.$refs.uForm2.validate().then(res => {
						console.log("校验通过")
						this.loading = true
						uni.showLoading({
							title: '提交中...'
						})
						this.$request({
							method: 'POST',
							header: {
								"Content-Type": "application/json"
							},
							data: {
								openid: this.openid,
								...this.form,
								type: this.tabIndex + 1 + '',
								list: this.list
							},
							url: '/appoint/add'
						}).then(res => {
							this.$refs.uNotify.show({
								top: 10,
								type: 'success',
								message: '预约成功',
								duration: 1000 * 1,
								safeAreaInsetTop: true
							})
							setTimeout(() => {
								uni.redirectTo({
									url: "/pages/reservation/reservation"
								})
							}, 1100)
						}).catch(e => {
							uni.showModal({
								title: '温馨提示',
								content: e.msg,
								showCancel: false
							})
						}).finally(()=>{
							uni.hideLoading()
							this.loading = false
						})
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.input-placeholder{
		font-size: 12px;
	}
	.add-container {
		width: 100%;
		min-height: 100vh;
		background: #f3f3f3;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 30rpx;
		// justify-content: center;

		.mg-top30 {
			margin-top: 16rpx;
		}

		.header {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #888888;
			margin-bottom: 16rpx;
			// height: 70rpx;

			.logo {
				margin-left: -48rpx;
				height: 40rpx;
				width: 40rpx;
				line-height: 40rpx;
				font-size: 28rpx;
				border: 1px solid #3cbfad;
				color: #3cbfad;
				text-align: center;
				border-radius: 50%;
			}

			.title {
				// height: 40rpx;
				// line-height: 40rpx;
				margin-left: 10rpx;
				// margin-bottom: 20rpx;
			}

		}

		.submit {
			width: 94%;
			margin-top: 40rpx;
			margin-bottom: 60rpx;
		}

		.form-container {
			background: #fff;
			border-radius: 10rpx;
			padding: 20rpx 40rpx 30rpx 60rpx;
			width: 80%;
		}



	}
</style>